package org.springblade.modules.customer.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.BizConstant;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.exception.AssertServiceUtil;
import org.springblade.common.exception.BizException;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.mp.utils.UpdateWrapperUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.customer.entity.Customer;
import org.springblade.modules.customer.form.CustomerForm;
import org.springblade.modules.customer.mapper.CustomerMapper;
import org.springblade.modules.customer.service.ICustomerService;
import org.springframework.stereotype.Service;

/**
 * 客户表 服务实现类
 *
 * @author armyant
 * @since 2024-04-21
 */
@Service
@AllArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

	private final BladeRedis bladeRedis;

	@Override
	public void save(CustomerForm form) throws BizException {
		// 保存数据
		Customer entity = BeanUtil.copy(form, Customer.class);
		AssertServiceUtil.notNull(entity, BizConstant.SERVICE_RECOED_NOT_EXIST);
		if (this.count(Wrappers.<Customer>lambdaQuery().eq(Customer::getMobile, entity.getMobile())) > 0) {
			BizException.throwEx(BizConstant.SERVICE_DUPLICATE_PHONE_NUMBER);
		}
		entity.setCode(CommonUtil.getDataNo(bladeRedis, CommonConstant.DATA_PREFIX_CUSTOMER));
		this.save(entity);
	}

	@Override
	public void editByPrimaryKey(CustomerForm form, Long id) throws BizException {
		// 校验数据存在
		AssertServiceUtil.isTrue(
			this.count(Wrappers.<Customer>lambdaQuery().eq(Customer::getId, id)) == 0,
			BizConstant.SERVICE_RECOED_NOT_EXIST
		);
		// 处理表单
		Customer entity = BeanUtil.copy(form, Customer.class);
		AssertServiceUtil.notNull(entity, BizConstant.SERVICE_RECOED_NOT_EXIST);

		// 处理更新的数据
		LambdaUpdateWrapper<Customer> updateWrapper = UpdateWrapperUtil
			.buildUpdateWrapperExclude(entity)
			.lambda().eq(Customer::getId, id);

		// 更新数据
		this.updateById(entity);
	}

	@Override
	public void deleteByPrimaryKey(Long id) throws BizException {
		// 校验数据存在
		AssertServiceUtil.isTrue(
			this.count(Wrappers.<Customer>lambdaQuery().eq(Customer::getId, id)) == 0,
			BizConstant.SERVICE_RECOED_NOT_EXIST
		);
		this.removeById(id);
	}
}
